import React from "react";
import "./loading.less";

type LoadingProps = { color?: string | CanvasGradient | CanvasPattern; size?: string | number; style?: React.CSSProperties; className?:string }

export function Loading(props: LoadingProps) {
    const ref = (e:HTMLCanvasElement):void => {
        if(!e) {
            return;
        }
        let canvas = e;
        let ctx = canvas.getContext("2d") as CanvasRenderingContext2D; 
        let start:number = 0;
        let end:number = 0;
        let add:number = 3;
        let cw:number = canvas.width;
        let ch:number = canvas.height;
        let fps:number = 60;
        setInterval(() => {
            ctx.setTransform(1,0,0,1,0,0);
            ctx.clearRect(0,0,cw,ch);
            ctx.beginPath();
            ctx.lineWidth = cw/15;
            ctx.strokeStyle = props.color as string | CanvasGradient | CanvasPattern;
            ctx.arc(cw/2, ch/2, cw/2-cw/20, (start/100) * Math.PI, (end/100) * Math.PI);
            ctx.stroke();
            setEndStartAndDeg();
        }, 1000/fps);
        function setEndStartAndDeg():void {
            if(end % 150 !== 0) {
                end=end+add;
            } else if(start < end) {
                start=start+add;
            } else {
                end = end + add;
            }
            if(start === 600) {
                start = 0;
                end = 0;
            }
        }
    }

    return <canvas
        className={"pcy-loading-ico" + " " + props.className} 
        id="demo" 
        width={props.size?props.size:30} 
        height={props.size?props.size:30}
        ref={ref}
        style={props.style}
    >

     </canvas>
}

